package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.publish;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.model.ImportRequest;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineFileService;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineWriteService;
import com.alibaba.citrus.cr.sales.plan.api.setting.SalesPlanScItemQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.BatchQuerySalesPlanScItemRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanLineImportRequest;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanLineStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanModelEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanScItemExtendRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanAdjustDetailSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemExtendSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.publish.SalesPlanPublishFileService;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.publish.SalesPlanPublishWriteService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.BatchQuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.EditSalesPlanPublishRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryPlanScItemExtendRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanAdjustTaskImportRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanDetailBatchQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanImportRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanLineDepartmentTaskRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanLineTaskImportRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.LoadSalesPlanDetailListRequest;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.LoadSalesPlanDetailRequest;
import com.epoch.app.bcorder.sales_plan.salesplandetail.model.SalesPlanDetail;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressIndex;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-11-14 11:36
 */
@Component
public class SalesPlanPublishFileServiceImpl implements SalesPlanPublishFileService {

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanPublishWriteService salesPlanPublishWriteService;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Resource
    private SalesPlanScItemExtendRepository salesPlanScItemExtendRepository;

    @Resource
    private SalesPlanScItemQueryService salesPlanScItemQueryService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;
    @Resource
    SalesPlanLineFileService salesPlanLineFileService;

    private static final Log log = Log.getLogger(SalesPlanPublishFileServiceImpl.class);

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanLineTaskImportRequest>> salesPlanLineTaskImportHandle(
        List<SalesPlanLineTaskImportRequest> requestList, SalesPlanImportRequest salesPlanImportRequest) {

        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        //校验必传参数
        HashSet<String> checkmultyItem = new HashSet<>();
        //1027调整为直接去插入，如果插入发现是重复的， 则去更新
        List<SalesPlanLineTaskImportRequest> checkRequestListWithId = new ArrayList<>();
        List<SalesPlanLineTaskImportRequest> checkRequestListWithoutId = new ArrayList<>();
        for (SalesPlanLineTaskImportRequest salesPlanLineTaskImportRequest : requestList) {
            String unikey = salesPlanLineTaskImportRequest.getCustomerCode() + salesPlanLineTaskImportRequest
                .getScItemId() + salesPlanLineTaskImportRequest.getCustomerAddress();
            PageQueryPlanLineRequest pageQueryPlanLineRequest = new PageQueryPlanLineRequest();
            pageQueryPlanLineRequest.setPlanId(salesPlanImportRequest.getPlanId());
            PageResult<List<SalesPlanLineSDO>> result = salesPlanLineRepository.pageQuerySalesPlanLineList(
                pageQueryPlanLineRequest);

            if (checkmultyItem.contains(unikey)) {
                salesPlanLineTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-046", null).getDisplayErrorMessage());
                continue;
            }
            if (null == salesPlanLineTaskImportRequest.getMonthFirstTaskCount()) {
                salesPlanLineTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-024", null).getDisplayErrorMessage());
                continue;
            }
            if (null == salesPlanLineTaskImportRequest.getMonthMiddleTaskCount()) {
                salesPlanLineTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-025", null).getDisplayErrorMessage());
                continue;
            }
            if (null == salesPlanLineTaskImportRequest.getMonthLastTaskCount()) {
                salesPlanLineTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-026", null).getDisplayErrorMessage());
                continue;
            }
            checkmultyItem.add(unikey);
        }

        for (SalesPlanLineTaskImportRequest salesPlanLineTaskImportRequest : requestList) {
            SalesPlanLineTaskImportRequest isExist= getExistPlanLineSDO(salesPlanLineTaskImportRequest,salesPlanImportRequest);
            if(StringUtils.isNotBlank(isExist.getErrorMessage())){
                salesPlanLineTaskImportRequest.setErrorMessage(isExist.getErrorMessage());
                continue;
            }
            if(StringUtils.isBlank(isExist.getId())){
                checkRequestListWithoutId.add(salesPlanLineTaskImportRequest);
            }else{
                checkRequestListWithId.add(salesPlanLineTaskImportRequest);
            }
        }
        if (checkRequestListWithId.size() == 0 && checkRequestListWithoutId.size() == 0) {
            return Result.success(requestList);
        }
        Set<Long> idSet = checkRequestListWithId.stream().map(SalesPlanLineTaskImportRequest::getId).map(Long::valueOf)
            .collect(Collectors.toSet());
        SalesPlanDetailBatchQueryRequest salesPlanDetailBatchQueryRequest = new SalesPlanDetailBatchQueryRequest();
        salesPlanDetailBatchQueryRequest.setIds(Lists.newArrayList(idSet));
        List<SalesPlanLineSDO> salesPlanLineSDOS = salesPlanLineRepository.batchQueryDetailByIds(
            salesPlanDetailBatchQueryRequest);
        if (CollectionUtils.isEmpty(salesPlanLineSDOS)) {
            //如果有id的查不到,按没有id处理，加入到无id列里
            checkRequestListWithoutId.addAll(checkRequestListWithId);
            checkRequestListWithId.clear();
        }
        Map<Long, SalesPlanLineSDO> salesPlanLineSDOMap = salesPlanLineSDOS.stream().collect(
            Collectors.toMap(SalesPlanLineSDO::getId, a -> a, (a, b) -> a));
        //数据填充
        for (SalesPlanLineTaskImportRequest salesPlanLineTaskImportRequest : checkRequestListWithId) {
            SalesPlanLineSDO salesPlanLineSDO = salesPlanLineSDOMap.get(Optional.ofNullable(
                salesPlanLineTaskImportRequest.getId()).map(Long::valueOf).orElse(null));
            if (Objects.isNull(salesPlanLineSDO)) {
                checkRequestListWithoutId.add(salesPlanLineTaskImportRequest);
                continue;
            }
            SalesPlanLineSDO sdo = SalesPlanLineSDO.builder().build();
            BeanUtils.copyProperties(salesPlanLineSDO, sdo);
            //查一下是否存在 存在即更新
            sdo.setMonthFirstTaskCount(salesPlanLineTaskImportRequest.getMonthFirstTaskCount());
            sdo.setMonthMiddleTaskCount(salesPlanLineTaskImportRequest.getMonthMiddleTaskCount());
            sdo.setMonthLastTaskCount(salesPlanLineTaskImportRequest.getMonthLastTaskCount());
            Integer taskCount = salesPlanLineTaskImportRequest.getMonthFirstTaskCount()
                + salesPlanLineTaskImportRequest.getMonthMiddleTaskCount() + salesPlanLineTaskImportRequest
                .getMonthLastTaskCount();
            sdo.setTaskCount(taskCount);
            EditSalesPlanPublishRequest editSalesPlanPublishRequest = new EditSalesPlanPublishRequest();
            editSalesPlanPublishRequest.setId(sdo.getId());
            editSalesPlanPublishRequest.setTaskCount(sdo.getTaskCount());
            editSalesPlanPublishRequest.setMonthFirstTaskCount(sdo.getMonthFirstTaskCount());
            editSalesPlanPublishRequest.setMonthMiddleTaskCount(sdo.getMonthMiddleTaskCount());
            editSalesPlanPublishRequest.setMonthLastTaskCount(sdo.getMonthLastTaskCount());
            try {
                salesPlanPublishWriteService.editSalesPlanDetailForImport(editSalesPlanPublishRequest);
            } catch (FacadeException e) {
                log.error("导入客户任务量异常", e);
                salesPlanLineTaskImportRequest.setErrorMessage(e.getErrorMessage());
                continue;
            }
        }
        for (SalesPlanLineTaskImportRequest x : checkRequestListWithoutId) {
            SalesPlanLineImportRequest y = new SalesPlanLineImportRequest();
            BeanUtils.copyProperties(x, y);
            y.setPlanId(salesPlanImportRequest.getPlanId());
            Result<List<SalesPlanLineImportRequest>> importResult = salesPlanLineFileService.salesPlanLineImportHandle(
                Lists.newArrayList(y), salesPlanImportRequest);
            if (importResult.isSuccess() && CollectionUtils.isNotEmpty(importResult.getResult())) {
                if (StringUtils.isNotBlank(importResult.getResult().get(0).getErrorMessage())) {
                    x.setErrorMessage(importResult.getResult().get(0).getErrorMessage());
                }
            }
            if (!importResult.isSuccess()) {
                x.setErrorMessage(importResult.getMessage());
            }
        }
        return Result.success(requestList);
    }

    public SalesPlanLineTaskImportRequest getExistPlanLineSDO(SalesPlanLineTaskImportRequest salesPlanLineImportRequest,
        SalesPlanImportRequest salesPlanImportRequest) {
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> itemGroupSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        if (Strings.isBlank(salesPlanLineImportRequest.getCustomerCode())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-004-02-15-005", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        } else {
            salesPlanLineImportRequest.setCustomerCode(salesPlanLineImportRequest.getCustomerCode().trim());
        }

        if (Strings.isBlank(salesPlanLineImportRequest.getCustomerAddress())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-004-02-15-006", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        } else {
            salesPlanLineImportRequest.setCustomerAddress(salesPlanLineImportRequest.getCustomerAddress().trim());
        }

        if (Strings.isBlank(salesPlanLineImportRequest.getScItemId())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        } else {
            salesPlanLineImportRequest.setScItemId(salesPlanLineImportRequest.getScItemId().trim());
        }

        if (Strings.isBlank(salesPlanLineImportRequest.getChannelCode())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-001-00-16-030", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        } else {
            salesPlanLineImportRequest.setChannelCode(salesPlanLineImportRequest.getChannelCode().trim());
        }

        if (Strings.isBlank(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-001-00-16-029", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        } else {
            salesPlanLineImportRequest.setOrgSalesOrganizationOutCode(
                salesPlanLineImportRequest.getOrgSalesOrganizationOutCode().trim());
        }

        if (Strings.isBlank(salesPlanLineImportRequest.getItemGroup())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-001-00-16-031", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        } else {
            salesPlanLineImportRequest.setItemGroup(salesPlanLineImportRequest.getItemGroup().trim());
        }
        customerAddressSet.add(salesPlanLineImportRequest.getCustomerAddress());
        customerSet.add(salesPlanLineImportRequest.getCustomerCode());
        channelCodeSet.add(salesPlanLineImportRequest.getChannelCode());
        scItemSet.add(salesPlanLineImportRequest.getScItemId());
        itemGroupSet.add(salesPlanLineImportRequest.getItemGroup());
        orgSalesOrganizationCodeSet.add(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode());

        // 查询货品
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemSet);
        if (scItemMap == null) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }

        // 销售组织外部编码 置换 内部ID
        Map<String, com.epoch.app.crplatformenhance.sdo.OrganizationSDO> organizationMapByOutCode
            = salesPlanOutCommonService.getOrganizationMapByOutCode(orgSalesOrganizationCodeSet);
        if (organizationMapByOutCode == null) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }

        // 查询客户地址 (五键唯一)
        Set<String> organizationIdList = organizationMapByOutCode.values().stream().map(
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toSet());
        Map<String, CustomerAddressIndex> customerAddressMap = salesPlanOutCommonService.getCustomerAddressByFive(
            customerAddressSet, customerSet, organizationIdList, channelCodeSet, itemGroupSet);
        if (customerAddressMap == null) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }

        // 获取客户地址对应的组织
        com.epoch.app.crplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(
            salesPlanLineImportRequest.getOrgSalesOrganizationOutCode());
        if (organization == null) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        CustomerAddressIndex customerAddressSDO = customerAddressMap.get(
            salesPlanLineImportRequest.getCustomerCode() + salesPlanLineImportRequest.getCustomerAddress()
                + organization.getId() + salesPlanLineImportRequest.getChannelCode() + salesPlanLineImportRequest
                .getItemGroup());
        if (Objects.isNull(customerAddressSDO)) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        // 权限校验
        if (salesPlanImportRequest.getBizType() == null && StringUtil.isBlank(salesPlanImportRequest.getBizId())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-002-02-15-034", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        // 业务单元以上的能查看所有数据(权限控制)
        if (salesPlanImportRequest.getBizType() >= SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
            SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(
                salesPlanImportRequest.getBizType());
            if (byOrganizationType == null) {
                salesPlanLineImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-002-02-15-035", null).getDisplayErrorMessage());
                return salesPlanLineImportRequest;
            }
            boolean isContinue = false;
            switch (byOrganizationType) {
                case SALESMAN:
                    if (StringUtil.isBlank(customerAddressSDO.getPrincipal())) {
                        salesPlanLineImportRequest.setErrorMessage(
                            ErrorMessage.code("OTS-02-002-02-15-028", null).getDisplayErrorMessage());
                        isContinue = true;
                    } else {
                        if (!customerAddressSDO.getPrincipal().equals(salesPlanImportRequest.getBizId())) {
                            salesPlanLineImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-033", null).getDisplayErrorMessage());
                            isContinue = true;
                        }
                    }
                    break;
                case SALES_DEPARTMENT:
                    if (StringUtil.isBlank(customerAddressSDO.getOrgSaleDepartmentCode())) {
                        salesPlanLineImportRequest.setErrorMessage(
                            ErrorMessage.code("OTS-02-002-02-15-029", null).getDisplayErrorMessage());
                        isContinue = true;
                    } else {
                        if (!customerAddressSDO.getOrgSaleDepartmentCode().equals(
                            salesPlanImportRequest.getBizId())) {
                            salesPlanLineImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                            isContinue = true;
                        }
                    }
                    break;
                case SALES_CHANNEL:
                    if (StringUtil.isBlank(customerAddressSDO.getOrgSaleChannelCode())) {
                        salesPlanLineImportRequest.setErrorMessage(
                            ErrorMessage.code("OTS-02-002-02-15-030", null).getDisplayErrorMessage());
                        isContinue = true;
                    } else {
                        if (!customerAddressSDO.getOrgSaleChannelCode().equals(salesPlanImportRequest.getBizId())) {
                            salesPlanLineImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                            isContinue = true;
                        }
                    }
                    break;
                case SALES_ORGANIZATION:
                    if (StringUtil.isBlank(customerAddressSDO.getOrgSaleOrganizationCode())) {
                        salesPlanLineImportRequest.setErrorMessage(
                            ErrorMessage.code("OTS-02-002-02-15-031", null).getDisplayErrorMessage());
                        isContinue = true;
                    } else {
                        if (!customerAddressSDO.getOrgSaleOrganizationCode().equals(
                            salesPlanImportRequest.getBizId())) {
                            salesPlanLineImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                            isContinue = true;
                        }
                    }
                    break;
                case BUSINESS_UNIT:
                    if (StringUtil.isBlank(customerAddressSDO.getOrgBussinessUnitCode())) {
                        salesPlanLineImportRequest.setErrorMessage(
                            ErrorMessage.code("OTS-02-002-02-15-032", null).getDisplayErrorMessage());
                        isContinue = true;
                    } else {
                        if (!customerAddressSDO.getOrgBussinessUnitCode().equals(
                            salesPlanImportRequest.getBizId())) {
                            salesPlanLineImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                            isContinue = true;
                        }
                    }
                    break;
                default:
            }
        }

        //            ScItemSDO scItem = scItemMap.get(salesPlanLineImportRequest.getScItemId());
        //            if (Objects.isNull(scItem)) {
        //                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-001",
        //                null).getDisplayErrorMessage());
        //                continue;
        //            }
        if (StringUtil.isNotEmpty(customerAddressSDO.getOrgBussinessUnitCode())) {
            salesPlanLineImportRequest.setOrgBusinessUnitCode(customerAddressSDO.getOrgBussinessUnitCode());
        }
        if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleOrganizationCode())) {
            salesPlanLineImportRequest.setOrgSaleOrganizationCode(customerAddressSDO.getOrgSaleOrganizationCode());
        }
        if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleChannelCode())) {
            salesPlanLineImportRequest.setOrgSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
        }

        // 计划货品范围
        List<String> scItemIdList = scItemMap.values().stream().map(ScItemSDO::getScItemId).distinct().collect(
            Collectors.toList());
        List<String> orgBusinessUnitCodeList = Arrays.asList(salesPlanLineImportRequest.getOrgBusinessUnitCode());
        List<String> orgSaleOrganizationCodeList = Arrays.asList(salesPlanLineImportRequest.getOrgSaleOrganizationCode());
        List<String> orgBusinessChannelCodeList = Arrays.asList(salesPlanLineImportRequest.getChannelCode());

        BatchQuerySalesPlanScItemRequest batchQuerySalesPlanScItemRequest = new BatchQuerySalesPlanScItemRequest();
        batchQuerySalesPlanScItemRequest.setScItemIds(scItemIdList);
        batchQuerySalesPlanScItemRequest.setOrgBusinessUnitCodeList(orgBusinessUnitCodeList);
        batchQuerySalesPlanScItemRequest.setOrgSaleOrganizationCodeList(orgSaleOrganizationCodeList);
        batchQuerySalesPlanScItemRequest.setOrgBusinessChannelCodeList(orgBusinessChannelCodeList);
        batchQuerySalesPlanScItemRequest.setStatus(1);// 启用状态的数据
        Result<List<SalesPlanScItemSDO>> salesPlanScItemResult = salesPlanScItemQueryService.batchQuerySalesPlanScItem(
            batchQuerySalesPlanScItemRequest);
        if (salesPlanScItemResult == null || CollectionUtils.isEmpty(salesPlanScItemResult.getResult())) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        log.info("salesPlanLineImportHandle_batchQuerySalesPlanScItem_request={},result={},size={}",
            JSONObject.toJSONString(batchQuerySalesPlanScItemRequest), JSONObject.toJSONString(salesPlanScItemResult),
            salesPlanScItemResult.getResult().size());
        //        Map<String, com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemSDO> salesPlanScItemMap =
        //        salesPlanScItemResult.getResult().stream().collect(Collectors.toMap(x -> x.getOrgBusinessUnitCode()
        //        + x.getOrgSalesOrganizationCode() + x.getOrgSalesChannelCode() + x.getScItemId(), a -> a, (a, b) ->
        //        a));
        Map<String, SalesPlanScItemSDO> salesPlanScItemMap = salesPlanScItemResult.getResult().stream().collect(
            Collectors.toMap(
                x -> x.getOrgBusinessUnitCode() + x.getOrgSalesOrganizationCode() + x.getOrgBusinessChannelCode() + x
                    .getScItemId(), a -> a, (a, b) -> a));
        // 数据填充
        com.epoch.app.crplatformenhance.sdo.OrganizationSDO organization2 = organizationMapByOutCode.get(
            salesPlanLineImportRequest.getOrgSalesOrganizationOutCode());
        // 地址
        CustomerAddressIndex customerAddressSDO2 = customerAddressMap.get(
            salesPlanLineImportRequest.getCustomerCode() + salesPlanLineImportRequest.getCustomerAddress()
                + organization2.getId() + salesPlanLineImportRequest.getChannelCode() + salesPlanLineImportRequest
                .getItemGroup());
        ScItemSDO scItem = scItemMap.get(salesPlanLineImportRequest.getScItemId());
        if (Objects.isNull(scItem)) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        SalesPlanScItemSDO salesPlanScItemSDO = salesPlanScItemMap.get(
            customerAddressSDO2.getOrgBussinessUnitCode() + customerAddressSDO2.getOrgSaleOrganizationCode()
                + customerAddressSDO2.getChannelCode() + scItem.getScItemId());
        if (Objects.isNull(salesPlanScItemSDO)) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        if (salesPlanScItemSDO.getOutboundPrice() == null || salesPlanScItemSDO.getCostInsuranceFreight() == null) {
            salesPlanLineImportRequest.setErrorMessage(
                ErrorMessage.code("OTS-02-001-00-15-042", null).getDisplayErrorMessage());
            return salesPlanLineImportRequest;
        }
        PageQueryPlanLineRequest request = new PageQueryPlanLineRequest();
        request.setPlanId(salesPlanImportRequest.getPlanId());
        request.setCustomerAddressId(Objects.toString(customerAddressSDO.getId(), null));
        request.setScItemId(scItem.getScItemId());
        PageResult<List<SalesPlanLineSDO>> pageResult = salesPlanLineRepository.pageQuerySalesPlanLineList(request);
        if (CollectionUtils.isNotEmpty(pageResult.getContent())) {
            salesPlanLineImportRequest.setId(pageResult.getContent().get(0).getId().toString());
            return salesPlanLineImportRequest;
        }
        return salesPlanLineImportRequest;
    }

    @Override
    public Result<List<SalesPlanLineDepartmentTaskRequest>> salesPlanLineDepartmentTaskImport(
        List<SalesPlanLineDepartmentTaskRequest> requestList) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        //校验必传参数
        List<SalesPlanLineDepartmentTaskRequest> checkRequestList = new ArrayList<>();
        for (SalesPlanLineDepartmentTaskRequest salesPlanLineDepartmentTaskRequest : requestList) {
            if (Strings.isBlank(salesPlanLineDepartmentTaskRequest.getId())) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-002-00-15-018", null).getDisplayErrorMessage());
                continue;
            }
            //            if (Strings.isBlank(salesPlanLineDepartmentTaskRequest.getDepartmentCode())) {
            //                salesPlanLineDepartmentTaskRequest.setErrorMessage(ErrorMessage.code
            //                ("OTS-02-002-00-15-022", null).getDisplayErrorMessage());
            //                continue;
            //            }
            //            if (Strings.isBlank(salesPlanLineDepartmentTaskRequest.getScItemId())) {
            //                salesPlanLineDepartmentTaskRequest.setErrorMessage(ErrorMessage.code
            //                ("OTS-02-002-00-15-023", null).getDisplayErrorMessage());
            //                continue;
            //            }
            if (null == salesPlanLineDepartmentTaskRequest.getMonthFirstTaskCount()) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-024", null).getDisplayErrorMessage());
                continue;
            }
            if (null == salesPlanLineDepartmentTaskRequest.getMonthMiddleTaskCount()) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-025", null).getDisplayErrorMessage());
                continue;
            }
            if (null == salesPlanLineDepartmentTaskRequest.getMonthLastTaskCount()) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-004-01-15-026", null).getDisplayErrorMessage());
                continue;
            }
            checkRequestList.add(salesPlanLineDepartmentTaskRequest);
        }
        if (checkRequestList == null || checkRequestList.size() == 0) {
            return Result.success(requestList);
        }
        for (SalesPlanLineDepartmentTaskRequest salesPlanLineDepartmentTaskRequest : checkRequestList) {
            QueryPlanScItemExtendRequest queryPlanScItemExtendRequest = new QueryPlanScItemExtendRequest();
            String id = salesPlanLineDepartmentTaskRequest.getId();
            queryPlanScItemExtendRequest.setIds(Lists.newArrayList(id));
            List<SalesPlanScItemExtendSDO> salesPlanScItemExtendSDOS = salesPlanScItemExtendRepository
                .batchQueryPlanScItemExtend(queryPlanScItemExtendRequest);
            if (CollectionUtils.isEmpty(salesPlanScItemExtendSDOS)) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-002-00-16-021", null).getDisplayErrorMessage());
                continue;
            }
            SalesPlanScItemExtendSDO salesPlanScItemExtendSDO = salesPlanScItemExtendSDOS.get(0);
/*            String departmentCode = salesPlanLineDepartmentTaskRequest.getDepartmentCode();
            if (!departmentCode.equals(salesPlanScItemExtendSDO.getBizId())) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-024", null)
                .getDisplayErrorMessage());
                continue;
            }
            // 实际是外部编码查内部编码
            String scItemId = salesPlanLineDepartmentTaskRequest.getScItemId();
            SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
            Map searchReqDTO = new HashMap();
            searchReqDTO.put("outerIdList", Lists.newArrayList(scItemId));
            searchScItemRequest.setSearchReqDTO(searchReqDTO);
            Result<List<ScItemSDO>> listResult = baseDataService.searchScItem(searchScItemRequest);
            if (null != listResult && null != listResult.getResult()) {
                if (listResult.getResult().size() == 0) {
                    salesPlanLineDepartmentTaskRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-025",
                    null).getDisplayErrorMessage());
                    continue;
                } else {
                    ScItemSDO scItemSDO = listResult.getResult().get(0);
                    // 实际内部id
                    String scItemIdIn = scItemSDO.getScItemId();
                    if (!scItemIdIn.equals(salesPlanScItemExtendSDO.getScItemId())) {
                        salesPlanLineDepartmentTaskRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-025",
                        null).getDisplayErrorMessage());
                        continue;
                    }
                }
            }*/
            EditSalesPlanPublishRequest editSalesPlanPublishRequest = new EditSalesPlanPublishRequest();
            BeanUtils.copyProperties(salesPlanScItemExtendSDO, editSalesPlanPublishRequest);
            editSalesPlanPublishRequest.setMonthFirstTaskCount(
                salesPlanLineDepartmentTaskRequest.getMonthFirstTaskCount());
            editSalesPlanPublishRequest.setMonthMiddleTaskCount(
                salesPlanLineDepartmentTaskRequest.getMonthMiddleTaskCount());
            editSalesPlanPublishRequest.setMonthLastTaskCount(
                salesPlanLineDepartmentTaskRequest.getMonthLastTaskCount());
            Integer taskCount = salesPlanLineDepartmentTaskRequest.getMonthFirstTaskCount()
                + salesPlanLineDepartmentTaskRequest.getMonthMiddleTaskCount() + salesPlanLineDepartmentTaskRequest
                .getMonthLastTaskCount();
            editSalesPlanPublishRequest.setTaskCount(taskCount);
            try {
                salesPlanPublishWriteService.editSalesPlanPublishForImport(editSalesPlanPublishRequest);
            } catch (FacadeException e) {
                salesPlanLineDepartmentTaskRequest.setErrorMessage(e.getErrorMessage());
                continue;
            }
        }
        return Result.success(checkRequestList);
    }

    @Override
    public Result<List<SalesPlanAdjustTaskImportRequest>> salesPlanAdjustTaskImportHandle(
        List<SalesPlanAdjustTaskImportRequest> requestList, SalesPlanImportRequest salesPlanImportRequest) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        Set<String> itemGroupSet = Sets.newHashSet();
        //校验必传参数
        List<SalesPlanAdjustTaskImportRequest> checkRequestList = new ArrayList<>();
        for (SalesPlanAdjustTaskImportRequest salesPlanAdjustTaskImportRequest : requestList) {
            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getAdjustId())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-018", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustTaskImportRequest.setAdjustId(salesPlanImportRequest.getAdjustId().trim());
            }

            if (!salesPlanAdjustTaskImportRequest.getAdjustId().trim().equals(salesPlanImportRequest.getAdjustId())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-025", null).getDisplayErrorMessage());
                continue;
            }

            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getCustomerCode())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-019", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustTaskImportRequest.setCustomerCode(
                    salesPlanAdjustTaskImportRequest.getCustomerCode().trim());
            }

            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getCustomerAddress())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-020", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustTaskImportRequest.setCustomerAddress(
                    salesPlanAdjustTaskImportRequest.getCustomerAddress().trim());
            }

            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getOuterId())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-021", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanAdjustTaskImportRequest.getMonthFirstAdjustReturnCount()) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-022", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanAdjustTaskImportRequest.getMonthMiddleAdjustReturnCount()) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-023", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanAdjustTaskImportRequest.getMonthLastAdjustReturnCount()) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-024", null).getDisplayErrorMessage());
                continue;
            }

            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getChannelCode())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-001-00-16-030", null).getDisplayErrorMessage());
                continue;
            }

            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getOrgSalesOrganizationOutCode())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-001-00-16-029", null).getDisplayErrorMessage());
                continue;
            }

            if (Strings.isBlank(salesPlanAdjustTaskImportRequest.getItemGroup())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-001-00-16-031", null).getDisplayErrorMessage());
                continue;
            }

            scItemSet.add(salesPlanAdjustTaskImportRequest.getOuterId());
            customerAddressSet.add(salesPlanAdjustTaskImportRequest.getCustomerAddress());
            customerSet.add(salesPlanAdjustTaskImportRequest.getCustomerCode());
            orgSalesOrganizationCodeSet.add(salesPlanAdjustTaskImportRequest.getOrgSalesOrganizationOutCode());
            channelCodeSet.add(salesPlanAdjustTaskImportRequest.getChannelCode());
            itemGroupSet.add(salesPlanAdjustTaskImportRequest.getItemGroup());
            checkRequestList.add(salesPlanAdjustTaskImportRequest);
        }
        if (checkRequestList.size() == 0) {
            return Result.success(requestList);
        }

        //销售组织外部编码 置换 内部ID
        Map<String, com.epoch.app.crplatformenhance.sdo.OrganizationSDO> organizationMapByOutCode
            = salesPlanOutCommonService.getOrganizationMapByOutCode(orgSalesOrganizationCodeSet);
        if (organizationMapByOutCode == null) {
            log.error(
                "SalesPlanPublishFileServiceImpl.salesPlanAdjustTaskImportHandle.orgSalesOrganizationCodeResult "
                    + "nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList,
                ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        //批量查货品，换取scItemId
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemSet);
        if (scItemMap == null) {
            log.error("SalesPlanPublishFileServiceImpl.salesPlanAdjustTaskImportHandle.scItemResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList,
                ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        //客户收获地址
        //查询 客户地址 (五键唯一)
        Set<String> organizationIdList = organizationMapByOutCode.values().stream().map(
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toSet());
        Map<String, CustomerAddressIndex> customerAddressMap = salesPlanOutCommonService.getCustomerAddressByFive(
            customerAddressSet, customerSet, organizationIdList, channelCodeSet, itemGroupSet);
        if (customerAddressMap == null) {
            log.error(
                "SalesPlanPublishFileServiceImpl.salesPlanAdjustTaskImportHandle.customerAddressResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList,
                ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        //获取客户地址对应的组织
        List<SalesPlanAdjustTaskImportRequest> checkSalesPlanAdjustTaskImportRequest = new ArrayList<>();
        for (SalesPlanAdjustTaskImportRequest salesPlanAdjustTaskImportRequest : checkRequestList) {
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(
                salesPlanAdjustTaskImportRequest.getOrgSalesOrganizationOutCode());
            if (organization == null) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
                continue;
            }
            CustomerAddressIndex customerAddressSDO = customerAddressMap.get(
                salesPlanAdjustTaskImportRequest.getCustomerCode() + salesPlanAdjustTaskImportRequest
                    .getCustomerAddress() + organization.getId() + salesPlanAdjustTaskImportRequest.getChannelCode()
                    + salesPlanAdjustTaskImportRequest.getItemGroup());
            if (Objects.isNull(customerAddressSDO)) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
                continue;
            }
            //权限校验
            if (salesPlanImportRequest.getBizType() == null && StringUtil.isBlank(salesPlanImportRequest.getBizId())) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-002-02-15-007", null).getDisplayErrorMessage());
                continue;
            }
            //业务单元以上的能查看所有数据(权限控制)
            if (salesPlanImportRequest.getBizType() >= SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(
                    salesPlanImportRequest.getBizType());
                if (byOrganizationType == null) {
                    salesPlanAdjustTaskImportRequest.setErrorMessage(
                        ErrorMessage.code("OTS-02-002-02-15-007", null).getDisplayErrorMessage());
                    continue;
                }
                boolean isContinue = false;
                switch (byOrganizationType) {
                    case SALESMAN:
                        if (StringUtil.isBlank(customerAddressSDO.getPrincipal())) {
                            salesPlanAdjustTaskImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-028", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getPrincipal().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustTaskImportRequest.setErrorMessage(
                                    ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_DEPARTMENT:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleDepartmentCode())) {
                            salesPlanAdjustTaskImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-029", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleDepartmentCode().equals(
                                salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustTaskImportRequest.setErrorMessage(
                                    ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_CHANNEL:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleChannelCode())) {
                            salesPlanAdjustTaskImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-030", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleChannelCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustTaskImportRequest.setErrorMessage(
                                    ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_ORGANIZATION:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleOrganizationCode())) {
                            salesPlanAdjustTaskImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-031", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleOrganizationCode().equals(
                                salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustTaskImportRequest.setErrorMessage(
                                    ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case BUSINESS_UNIT:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgBussinessUnitCode())) {
                            salesPlanAdjustTaskImportRequest.setErrorMessage(
                                ErrorMessage.code("OTS-02-002-02-15-032", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgBussinessUnitCode().equals(
                                salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustTaskImportRequest.setErrorMessage(
                                    ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    default:
                }
                if (isContinue) {
                    continue;
                }
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgBussinessUnitCode())) {
                salesPlanAdjustTaskImportRequest.setOrgBusinessUnitCode(customerAddressSDO.getOrgBussinessUnitCode());
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleOrganizationCode())) {
                salesPlanAdjustTaskImportRequest.setOrgSaleOrganizationCode(
                    customerAddressSDO.getOrgSaleOrganizationCode());
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getChannelCode())) {
                salesPlanAdjustTaskImportRequest.setChannelCode(customerAddressSDO.getChannelCode());
            }
            checkSalesPlanAdjustTaskImportRequest.add(salesPlanAdjustTaskImportRequest);
        }
        if (checkSalesPlanAdjustTaskImportRequest.size() == 0) {
            return Result.success(requestList);
        }
        //货品范围
        List<String> scItemIdList = scItemMap.values().stream().map(ScItemSDO::getScItemId).distinct().collect(
            Collectors.toList());
        List<String> orgBusinessUnitCodeList = checkSalesPlanAdjustTaskImportRequest.stream().map(
            SalesPlanAdjustTaskImportRequest::getOrgBusinessUnitCode).distinct().collect(Collectors.toList());
        List<String> orgSaleOrganizationCodeList = checkSalesPlanAdjustTaskImportRequest.stream().map(
            SalesPlanAdjustTaskImportRequest::getOrgSaleOrganizationCode).distinct().collect(Collectors.toList());
        List<String> channelCodeList = checkSalesPlanAdjustTaskImportRequest.stream().map(
            SalesPlanAdjustTaskImportRequest::getChannelCode).distinct().collect(Collectors.toList());

        BatchQuerySalesPlanScItemRequest batchQuerySalesPlanScItemRequest = new BatchQuerySalesPlanScItemRequest();
        batchQuerySalesPlanScItemRequest.setScItemIds(scItemIdList);
        batchQuerySalesPlanScItemRequest.setOrgBusinessUnitCodeList(orgBusinessUnitCodeList);
        batchQuerySalesPlanScItemRequest.setOrgSaleOrganizationCodeList(orgSaleOrganizationCodeList);
        batchQuerySalesPlanScItemRequest.setOrgBusinessChannelCodeList(channelCodeList);
        //启用状态的数据
        batchQuerySalesPlanScItemRequest.setStatus(1);
        Result<List<SalesPlanScItemSDO>> salesPlanScItemResult = salesPlanScItemQueryService.batchQuerySalesPlanScItem(
            batchQuerySalesPlanScItemRequest);
        if (salesPlanScItemResult == null || !salesPlanScItemResult.isSuccess()
            || salesPlanScItemResult.getResult() == null || salesPlanScItemResult.getResult().size() == 0) {
            log.error(
                "SalesPlanPublishFileServiceImpl.salesPlanAdjustTaskImportHandle.salesPlanScItemResult nothingness");
            ImportRequest.setRequestErrorMessage(checkSalesPlanAdjustTaskImportRequest,
                ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        Map<String, SalesPlanScItemSDO> salesPlanScItemMap = salesPlanScItemResult.getResult().stream().collect(
            Collectors.toMap(
                x -> x.getOrgBusinessUnitCode() + x.getOrgSalesOrganizationCode() + x.getOrgBusinessChannelCode() + x
                    .getScItemId(), a -> a, (a, b) -> a));

        //校验调整ID是否存在
        Set<String> adjustIdSet = checkRequestList.stream().map(SalesPlanAdjustTaskImportRequest::getAdjustId).collect(
            Collectors.toSet());
        BatchQuerySalesPlanRequest batchQuerySalesPlanRequest = new BatchQuerySalesPlanRequest();
        batchQuerySalesPlanRequest.setIds(Lists.newArrayList(adjustIdSet));
        batchQuerySalesPlanRequest.setModel(SalesPlanModelEnum.ADJUST_MODEL.getModel());
        List<SalesPlanSDO> salesPlanSDOList = salesPlanRepository.batchQuerySalesPlan(batchQuerySalesPlanRequest);
        if (salesPlanSDOList == null || salesPlanSDOList.size() == 0) {
            log.error("SalesPlanPublishFileServiceImpl.salesPlanAdjustTaskImportHandle.salesPlanSDOList nothingness");
            ImportRequest.setRequestErrorMessage(checkSalesPlanAdjustTaskImportRequest,
                ErrorMessage.code("OTS-02-005-00-15-005", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        Map<Long, SalesPlanSDO> salesPlanSDOMap = salesPlanSDOList.stream().collect(
            Collectors.toMap(SalesPlanSDO::getId, a -> a, (a, b) -> a));

        //数据填充
        List<SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOList = new ArrayList<>();
        Map<String, SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOMap = new HashMap<>();
        for (SalesPlanAdjustTaskImportRequest salesPlanAdjustTaskImportRequest :
            checkSalesPlanAdjustTaskImportRequest) {
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(
                salesPlanAdjustTaskImportRequest.getOrgSalesOrganizationOutCode());
            //地址
            CustomerAddressIndex customerAddressSDO = customerAddressMap.get(
                salesPlanAdjustTaskImportRequest.getCustomerCode() + salesPlanAdjustTaskImportRequest
                    .getCustomerAddress() + organization.getId() + salesPlanAdjustTaskImportRequest.getChannelCode()
                    + salesPlanAdjustTaskImportRequest.getItemGroup());

            //货品
            ScItemSDO scItem = scItemMap.get(salesPlanAdjustTaskImportRequest.getOuterId());
            if (Objects.isNull(scItem)) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
                continue;
            }
            //计划货品
            SalesPlanScItemSDO salesPlanScItemSDO = salesPlanScItemMap.get(
                customerAddressSDO.getOrgBussinessUnitCode() + customerAddressSDO.getOrgSaleOrganizationCode()
                    + customerAddressSDO.getChannelCode() + scItem.getScItemId());
            if (Objects.isNull(salesPlanScItemSDO)) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
                continue;
            }
            //计划
            SalesPlanSDO planSDO = salesPlanSDOMap.get(Long.parseLong(salesPlanAdjustTaskImportRequest.getAdjustId()));
            if (Objects.isNull(planSDO)) {
                salesPlanAdjustTaskImportRequest.setErrorMessage(
                    ErrorMessage.code("OTS-02-005-00-15-005", null).getDisplayErrorMessage());
                continue;
            }
            //入参客户编码和查询出来的数据不相等不做处理
            //            if (!salesPlanAdjustTaskImportRequest.getCustomerCode().equals(customerAddressSDO
            //            .getCustomerCode())) {
            //                salesPlanAdjustTaskImportRequest.setErrorMessage(ErrorMessage.code
            //                ("OTS-01-004-02-15-001", null).getDisplayErrorMessage());
            //                continue;
            //            }
            //重复数据校验
            if (MapUtils.isNotEmpty(salesPlanAdjustDetailSDOMap)) {
                SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustDetailSDOMap.get(
                    salesPlanAdjustTaskImportRequest.getAdjustId() + salesPlanAdjustTaskImportRequest.getCustomerCode()
                        + salesPlanAdjustTaskImportRequest.getCustomerAddress() + salesPlanAdjustTaskImportRequest
                        .getOrgSalesOrganizationOutCode() + salesPlanAdjustTaskImportRequest.getChannelCode()
                        + salesPlanAdjustTaskImportRequest.getItemGroup() + salesPlanAdjustTaskImportRequest
                        .getOuterId());
                if (Objects.nonNull(salesPlanAdjustDetailSDO)) {
                    salesPlanAdjustTaskImportRequest.setErrorMessage(
                        ErrorMessage.code("OTS-02-002-00-15-019", null).getDisplayErrorMessage());
                    continue;
                }
            }
            SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = SalesPlanAdjustDetailSDO.builder().build();
            salesPlanAdjustDetailSDO.setAdjustId(
                Optional.ofNullable(Long.valueOf(salesPlanAdjustTaskImportRequest.getAdjustId())).orElse(0L));
            salesPlanAdjustDetailSDO.setCustomerCode(salesPlanAdjustTaskImportRequest.getCustomerCode());
            salesPlanAdjustDetailSDO.setCustomerAddress(salesPlanAdjustTaskImportRequest.getCustomerAddress());
            salesPlanAdjustDetailSDO.setOuterId(salesPlanAdjustTaskImportRequest.getOuterId());
            salesPlanAdjustDetailSDO.setScItemId(scItem.getScItemId());
            salesPlanAdjustDetailSDO.setMonthFirstAdjustReturnCount(
                salesPlanAdjustTaskImportRequest.getMonthFirstAdjustReturnCount());
            salesPlanAdjustDetailSDO.setMonthMiddleAdjustReturnCount(
                salesPlanAdjustTaskImportRequest.getMonthMiddleAdjustReturnCount());
            salesPlanAdjustDetailSDO.setMonthLastAdjustReturnCount(
                salesPlanAdjustTaskImportRequest.getMonthLastAdjustReturnCount());
            salesPlanAdjustDetailSDO.setCustomerAddressId(Objects.toString(customerAddressSDO.getId(), null));

            salesPlanAdjustDetailSDO.setPlanId(Optional.of(planSDO.getParentId().toString()).orElse(null));
            salesPlanAdjustDetailSDO.setChannelCode(
                Optional.ofNullable(customerAddressSDO.getChannelCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgBusinessUnitCode(
                Optional.ofNullable(customerAddressSDO.getOrgBussinessUnitCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgSalesOrganizationCode(
                Optional.ofNullable(customerAddressSDO.getOrgSaleOrganizationCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgSalesChannelCode(
                Optional.ofNullable(customerAddressSDO.getOrgSaleChannelCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgSalesDepartmentCode(
                Optional.ofNullable(customerAddressSDO.getOrgSaleDepartmentCode()).orElse(null));
            salesPlanAdjustDetailSDO.setManageEmployeeId(
                Optional.ofNullable(customerAddressSDO.getPrincipal()).orElse(null));
            salesPlanAdjustDetailSDO.setScItemGroup(
                Optional.ofNullable(salesPlanScItemSDO.getScItemGroup()).orElse(null));
            salesPlanAdjustDetailSDO.setScItemLeafCategoryId(
                Optional.ofNullable(salesPlanScItemSDO.getScItemLeafCategoryId()).orElse(null));
            salesPlanAdjustDetailSDO.setScItemRootCategoryId(
                Optional.ofNullable(salesPlanScItemSDO.getScItemRootCategoryId()).orElse(null));
            salesPlanAdjustDetailSDO.setCostInsuranceFreight(
                Optional.ofNullable(salesPlanScItemSDO.getCostInsuranceFreight()).orElse(0L));
            salesPlanAdjustDetailSDO.setBasicUnit(Optional.ofNullable(salesPlanScItemSDO.getBasicUnit()).orElse(null));
            salesPlanAdjustDetailSDO.setOutboundPrice(
                Optional.ofNullable(salesPlanScItemSDO.getOutboundPrice()).orElse(0L));
            salesPlanAdjustDetailSDOList.add(salesPlanAdjustDetailSDO);
            salesPlanAdjustDetailSDOMap.put(
                salesPlanAdjustTaskImportRequest.getAdjustId() + salesPlanAdjustTaskImportRequest.getCustomerCode()
                    + salesPlanAdjustTaskImportRequest.getCustomerAddress() + salesPlanAdjustTaskImportRequest
                    .getOrgSalesOrganizationOutCode() + salesPlanAdjustTaskImportRequest.getChannelCode()
                    + salesPlanAdjustTaskImportRequest.getItemGroup() + salesPlanAdjustTaskImportRequest.getOuterId(),
                salesPlanAdjustDetailSDO);
        }
        if (salesPlanAdjustDetailSDOList.size() == 0) {
            return Result.success(requestList);
        }
        salesPlanPublishWriteService.batchImportCreateSalesPlanTaskAdjustDetail(salesPlanAdjustDetailSDOList);
        return Result.success(requestList);
    }
}
